// Assignment #: 8
//         Name: 
//    StudentID:
//      Lecture: 1
//  Description: The ComputerParser class contains a static
//               method computerParser that takes a string
//               containing a computer's information and
//               create a computer object from it.

import java.util.*;

public class ComputerParser
 {

 /********************************************************
 The computerParser method will parse a string containing
 information on a computer, pull out the information,
 create a new computer object, set the attributes of the object,
 and return it to the calling method.
 ********************************************************/
 public static Computer computerParser(String lineToParse)
  {
   String brandName = new String("?");
   String price = new String("0.00");
   String memory = new String("0");
   String cpu = new String("0");
   String cpuType = new String("?");
   String cpuSpeed = new String("0");

   String[] tokens = lineToParse.split(":");
   

   Computer computer1 = new Computer();  //create a computer object to be returned

   try
    {
     //extract the brandname
     if (tokens.length > 0 && tokens[0].length() > 0)
      { 
       brandName = tokens[0].trim();
       computer1.setBrandName(brandName);
      }
     //extract cpu and assign it to the computer
     if (tokens.length > 1 && tokens[1].length() > 0)
      {
       cpu = tokens[1].trim();
       String[] tokens2 = tokens[1].split(",");

       //if cpuType exists in the string
       if (tokens2.length > 0 && tokens2[0].length() > 0)
         cpuType = tokens2[0].trim();

       //if cpuSpeed exists in the string
       if (tokens2.length > 1 && tokens2[1].length() > 0)
         cpuSpeed = tokens2[1].trim();

       computer1.setCPU(cpuType, cpuSpeed);
      }

      //if memory exists in the string, extract it and assign it to the computer
      if (tokens.length > 2 && tokens[2].length() > 0)
      {
       memory = tokens[2].trim();;
       computer1.setMemory(memory);
      }

     //if price exists in the string, extract it and assign it to the computer
     if (tokens.length > 3 && tokens[3].length() > 0)
      {
         price = tokens[3].trim();
         computer1.setPrice(Double.parseDouble(price));
      }

     return computer1;
    }
   //NumberFormatException can be thrown by parseInt or parseDouble method
   catch(NumberFormatException exception)
    {
     System.out.print("Invalid String\n");
     computer1 = new Computer(); // setting default computer object
     return computer1;
    }
  }

} // end of ComputerParser class
